package bookManage.Controller.servlet;

import bookManage.Model.entity.Book;
import bookManage.Model.service.ServiceImpl;
import bookManage.utils.DBUtil;
import bookManage.utils.JsonUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * @BelongsProject: library-management-system-master
 * @BelongsPackage: bookManage.Controller
 * @Author: yuan wang
 * @CreateTime: 2023-02-02  16:40
 * @Description: 编辑书籍的Servlet，用于修改之后提交的操作（在数据库中进行修改等等）
 * @Version: 1.0
 */
@WebServlet(name = "EditBookEnd", value = "/manager/BookShow/BookContent/EditBookEnd")
public class EditBookEnd extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String jsonString = String.valueOf(JsonUtil.getJson(req));
        JSONObject jsonObject = JSON.parseObject(jsonString);

        ServiceImpl service = new ServiceImpl();

        String oldNumber = jsonObject.getString("oldNumber");

        Book book = new Book();

        book.setBookName(jsonObject.getString("bookName"));
        book.setWriter(jsonObject.getString("writer"));
        book.setKind(jsonObject.getString("kind"));
        book.setNumber(jsonObject.getString("number"));
        book.setPublish(jsonObject.getString("publish"));
        book.setBookIntroduction(jsonObject.getString("bookIntroduction"));
        book.setWriterIntroduction(jsonObject.getString("writerIntroduction"));
        book.setPicture(jsonObject.getString("picture"));

        PrintWriter out = resp.getWriter();
        JSONObject object = new JSONObject();

        try {
            if (service.editBook(book, oldNumber) == 0) {
                object.put("code", "-1");
                object.put("message", "编辑失败");
                out.println(object);
            } else {
                object.put("code", "200");
                object.put("message", "编辑成功");
                out.println(object);
                //同样在这里可以做一个页面跳转，跳转到之前的BookContent页面
            }
        } catch (SQLException e) {
            object.put("code", "-1");
            object.put("message", "编辑失败");
            out.println(object);
        } finally {
            try {
                DBUtil.freeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doGet(req, resp);
    }
}
